define(["angularAMD", 'moment'], function (angularAMD, moment) {
    angularAMD.service('$StockInService', ['$rootScope', '$filter', '$translate', 'config', 'MMWService', '$mdDialog',
        function($rootScope, $filter, $translate, config, $MMWService, $mdDialog){
            var service = this;

            service.init = function(options){

                function QRCodeScanner(callback){
                    $rootScope.OpenScanner({
                        after : function(result){
                            if (callback)
                                callback(result.text)
                        },
                        exception: function(){
                            //目前裝置無法使用相機
                            $rootScope.showAlert($filter('translate')('common.msg.cant_use_camera'));
                        },
                        orientation : 'portrait'
                    });
                }

                //成品庫
                function loadProductWarehouse(dialog, callback){
                    var content = {
                        page_mode: 13,
                        query_condition_info: [
                            {column_name:'InventoryType', query_mode:'0', value: (dialog.type == 0) ? 1 : 3} // 良品 = 1 , 不良品 =3
                        ]
                    };
                    pageNumberInfoGet(content, function (response) {
                        $rootScope.showSelect({
                            title: $filter('translate')('common.msg.plz_select'),
                            label: function(item){
                                return item.page_no + ' ('+ item.page_name +')';
                            },
                            code: 'page_no',
                            selectCode: dialog.warehouseInfo.product_warehouse,
                            list: response,
                            confirm: function (selectItem, radioDialog) {
                                radioDialog.hide();
                                if (callback)
                                    callback(selectItem);
                            }
                        });
                    });
                }

                // 儲位
                function loadStorage(dialog, callback){
                    var content = {
                        page_mode: 14,
                        query_condition_info: [
                            {column_name:'InventoryNo', query_mode:'0', value: dialog.warehouseInfo.product_warehouse}
                        ]
                    };
                    pageNumberInfoGet(content, function (response) {
                        $rootScope.showSelect({
                            title: $filter('translate')('common.msg.plz_select'),
                            label: function(item){
                                return item.page_no + ' ('+ item.page_name +')';
                            },
                            code: 'page_no',
                            selectCode: dialog.warehouseInfo.storage,
                            list: response,
                            confirm: function (selectItem, radioDialog) {
                                radioDialog.hide();
                                if (callback)
                                    callback(selectItem);
                            }
                        });
                    });
                }

                // ERP單別
                function loadERP(dialog, callback){
                    $rootScope.showQueryList({
                        pageRecord: 50,
                        header : [
                            {label: $filter('translate')('mobile06.stock_in_info.erp_doc_type_no'), code:'page_no'},
                            {label: $filter('translate')('mobile06.stock_in_info.erp_doc_type_name'), code:'page_name'}
                        ],
                        query: function(conditions, feedback){
                            var content = {
                                doc_type: dialog.do_flag == 0 ? '1' : '6'
                            }; 
                            erpDocumentTypeGet(content, function(data){
                                feedback(data);
                            }); 
                        },
                        selectCode: dialog.warehouseInfo.erp_doc_type,
                        confirm : function(selectItem, radioDialog){
                            radioDialog.hide();
                            if (callback)
                                callback(selectItem);
                        }
                    });
                }

                function pageNumberInfoGet(content, callback){
                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_SYS.page_number_info_get',
                        content : content,
                        success : function(data){
                            if (callback)
                                callback(data.page_number_info_get);
                        }
                    });
                }

                function erpDocumentTypeGet(content, callback){
                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_SYS.erp_document_type_get',
                        content: content,
                        success: function (data) {
                            if (callback)
                                callback(data);
                        }
                    });
                }

                //良品入庫
                function warehousePlotProcess(content, callback){
                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_WIP.warehouse_plot_process',
                        content: content,
                        success: function (data, response) {
                            if (callback)
                                callback(response.Message);
                        }
                    });
                }

                function beforeOpenDialog(callback){
                    if (callback)
                        callback();                    
                }

                function beforeConfirm(dialog, callback){
                    if(dialog.type==0){
                        if(dialog.warehouseInfo.product_warehouse.length == 0) {
                            $rootScope.showAlert($filter('translate')('mobile06.msg.warehouse_or_storage_empty'));
                        } else {
                            if (callback)
                                callback();
                        }
                    } else if(dialog.type == 1){
                        if (callback)
                            callback();
                    }
                }

                function warehousePlotProcess_Imp(dialog, callback){
                    var msg = '';
                    var content = {
                        type: dialog.type,
                        product_warehouse: dialog.warehouseInfo.product_warehouse,
                        storage: dialog.warehouseInfo.storage,
                        erp_doc_type: dialog.warehouseInfo.erp_doc_type,
                        do_flag: dialog.do_flag,
                        plot_info_detail: []
                    };
                    for(var index in dialog.selectedList){
                        var item = dialog.selectedList[index];
                        //20220601 modify by panghx  for #110524 : 入库写入错误
                        var plot_info_detail = {
                            plot_no: item.plot_no,
                            op_no: item.op_no,
                            lot_serial: item.lot_serial,
                            plot_qty: item.storage_qty,
                            error_no: item.error_no,
                            do_flag: item.DOFlag,
                            product_no: item.item_no,
                            product_ver: item.item_ver,
                            qty: item.storage_qty, // 20230317 modify by Alan for #130356: 缺少qty造成入庫不成功
                        };

                        if(dialog.type == '0'){
                            if(item.joint_trigger == undefined){
                                plot_info_detail.joint_trigger = 'N';
                            } else {
                                plot_info_detail.joint_item_no = item.joint_item_no;
                                plot_info_detail.joint_item_unit_no = item.joint_item_unit_no;
                                plot_info_detail.joint_trigger = 'Y';
                            }
                        }
                        content.plot_info_detail.push(plot_info_detail);
                        //content.op_no = item.op_no;
                    }
                    if(msg == ''){
                        warehousePlotProcess(content, callback);
                    } else {
                        $rootScope.showAlert(msg);
                    }
                }

                function openDialog(){
                    $mdDialog.dialog(
                        'module/moduleMobile/program/mobile06/StockIn.tmp.html',
                        function (dialog) {
                            return {
                                type: options.type || '0', // 0:良品 1:不良品
                                do_flag: options.do_flag || '0', // 0: 製程完工 1: 製程未完工
                                warehouseInfo: {
                                    type: '', 
                                    product_warehouse: '', 
                                    storage: '',
                                    wo_no: '', 
                                    item_no: '', 
                                    plot_no: '', 
                                    erp_doc_type: '',
                                    plot_info_detail: []
                                },
                                selectedList: options.selectedList || [],
                                init: function () {
                                    // 20201222 modify by WeiTing for M#72157 - 如果選取的資料的倉庫和儲位都相同時，判斷是否跟下拉式選單的資料符合，符合就預設為此倉庫和儲位(搬到手機版)。
                                    var conditionvalue = 1;
                                    // 良品 = 1 , 不良品 = 3
                                    if(options.type == 0){
                                        conditionvalue = 1;
                                    } else {
                                        conditionvalue = 3;
                                    }
                                    pageNumberInfoGet({
                                        // 倉庫
                                        page_mode : '13',
                                        query_condition_info : [
                                            { column_name:'InventoryType', query_mode:'0', value:conditionvalue }
                                        ]
                                    }, function (response) {
                                        if(response && response.length > 0){
                                            for(var i = 0; i < response.length; i++){
                                                // 判斷倉庫是否跟下拉式選單的資料符合
                                                if(response[i].page_no === options.sameInventoryAndStorage.inventoryNo){
                                                    dialog.warehouseInfo.product_warehouse_name = response[i].page_name;
                                                    dialog.warehouseInfo.product_warehouse = response[i].page_no;

                                                    dialog.warehouseInfo.storage = '';
                                                    dialog.warehouseInfo.storage_display = '';
                                                    break;
                                                }
                                            }
                                        }    
                                        pageNumberInfoGet({
                                            // 儲位
                                            page_mode : 14, 
                                            query_condition_info : [
                                                {column_name:'InventoryNo', query_mode:'0', value:dialog.warehouseInfo.product_warehouse}
                                            ]
                                        }, function (response) {
                                            if(response && response.length > 0){
                                                for(var i = 0; i < response.length; i++){
                                                    // 判斷儲位是否跟下拉式選單的資料符合
                                                    if(response[i].page_no === options.sameInventoryAndStorage.storageSpacesNo){
                                                        dialog.warehouseInfo.storage = response[i].page_no;
                                                        dialog.warehouseInfo.storage_display = response[i].page_name;
                                                        break;
                                                    }
                                                }
                                            }
                                        });          
                                    });   
                                },
                                //成品庫
                                loadProductWarehouse: function () {
                                    loadProductWarehouse(dialog, function(selectItem){
                                        dialog.warehouseInfo.product_warehouse_name = selectItem.page_name;
                                        dialog.warehouseInfo.product_warehouse = selectItem.page_no;
                                        dialog.warehouseInfo.storage = '';
                                        dialog.warehouseInfo.storage_display = '';
                                    });
                                },
                                loadStorage: function () {
                                    if(dialog.warehouseInfo.product_warehouse != ''){
                                        loadStorage(dialog, function(selectItem){
                                            dialog.warehouseInfo.storage = selectItem.page_no;
                                            dialog.warehouseInfo.storage_display = selectItem.page_name;
                                        });
                                    } else {
                                        $rootScope.showAlert($filter('translate')('mobile06.msg.product_warehouse_empty'));
                                    }
                                },
                                loadERP: function () {
                                    loadERP(dialog, function(selectItem){
                                        dialog.warehouseInfo.erp_doc_type = selectItem.page_no;
                                        dialog.warehouseInfo.erp_doc_type_name = selectItem.page_name;
                                    });
                                },
                                QRCodeScanner: function(target_id){
                                    QRCodeScanner(function(text){
                                        dialog.warehouseInfo[target_id] = text;
                                        // 先不查名稱出來，直接顯示掃到的文字
                                        if(target_id == 'storage'){
                                            dialog.warehouseInfo.storage_display = text;
                                        } else if(target_id == 'product_warehouse'){
                                            dialog.warehouseInfo.product_warehouse_name = text;
                                        } else if(target_id == 'erp_doc_type'){
                                            dialog.warehouseInfo.erp_doc_type_name = text;
                                        }
                                    });
                                },
                                back: function(){
                                    dialog.hide();
                                },
                                confirm: function () {
                                    beforeConfirm(dialog, function(){
                                        warehousePlotProcess_Imp(dialog, function(msg){
                                            dialog.hide();

                                            // 20200902 modify by WeiTing for M#74338: 增加系統參數(WarehouseShowERPNo)來判斷入庫單號是否顯示確認跳窗，讓使用者記錄完後，自行關閉。
                                            if(config.cache.sys_parameter.WarehouseShowERPNo === 'Y'){
                                                $rootScope.showConfirm(msg, function(confirm_dialog){
                                                    confirm_dialog.hide();
                                                });
                                            } else {
                                                $rootScope.showToast(msg, 10);
                                            }

                                            if(options.callback)
                                                options.callback();
                                        });
                                    });
                                }
                            };
                        }
                    );
                } 
                
                beforeOpenDialog(function(){
                    openDialog();
                });
            };
        }
    ]);
});
